import Axios from "axios";

export function getUserInfo() {
    return new Promise((resolve, reject) => {
        let nowTime = new Date().getTime();
        let oldUserData = JSON.parse(localStorage.getItem("userData")) || undefined;
        if (oldUserData != undefined && nowTime - oldUserData.time < 86400000 * 7) {
            //用时间戳判断是否过期，默认为 7 天
            Axios.defaults.headers.common['Authorization'] = oldUserData.token;
            resolve(oldUserData.name);
        } else {
            let str = window.name
            window.name = ''
            let arr = str.split('|')
            let user = null;
            let isName = true;
            let patt = /^[1][3-9][\d]{9}/;

            let afterEqual = arr[0] || undefined
            let token = arr[1] || undefined
            if (patt.test(afterEqual)) {
                isName = false;
            }
            //正则判断是手机号登陆还是用户名登陆
            let Ev_users;
            isName ? Ev_users = { name: afterEqual } : Ev_users = { phone: afterEqual }
            //存token
            Axios.defaults.headers.common['Authorization'] = token;

            Axios.post('http://c7.cabc.top:8222/api/v1.0/jwt/APIjson/get/', {
                Ev_users,
            }).then(res => {
                if (res.data.data.code == 200) {
                    user = res.data.data.Ev_users || undefined;
                    let userData = {
                        token,
                        name: user.name,
                        id: user.id,
                        time: new Date().getTime(),
                    }
                    localStorage.setItem('userData', JSON.stringify(userData))
                } else {
                    this.$message('error');
                    reject(err);
                }
            }).catch(err => {
                console.log(err);
                reject(err)
            })

            //实现方法不太好，影响性能，待解决
            let times = 0;
            let getUser = setInterval(() => {
                times++;
                if (user !== null) {
                    console.log(user);
                    resolve(user.name)
                    clearInterval(getUser);
                }
                if (times >= 5) {
                    clearInterval(getUser);
                    resolve(undefined)
                }
            }, 1000);

        }
    })
}
//异步函数结果作为返回值的解决方案
export function test() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve('data')
        }, 3000);
    })
}